﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Polenter.Serialization;
using Sunny.UI;

namespace SmartMotion.Core.Mgrs
{
    public class FlowsMgr
    {
        #region 属性单例模式

        private static readonly Lazy<FlowsMgr> Instance = new Lazy<FlowsMgr>(() => new FlowsMgr());

        private FlowsMgr()
        {
            Flows = new List<Flow>();
            Path = Environment.CurrentDirectory + "\\Flows\\";

            if (!Directory.Exists(Path))
            {
                Directory.CreateDirectory(Path);
            }

            VarPath = Environment.CurrentDirectory + "\\VarPath\\";
            if (!Directory.Exists(VarPath))
            {
                Directory.CreateDirectory(VarPath);
            }
        }
        public static FlowsMgr Ins { get; } = Instance.Value;

        #endregion

        public string Path { get; set; }
        public string VarPath { get; set; }
        public List<Flow> Flows { get; }    

        public void SaveFlows()
        {
            foreach (var flow in Flows)
            {
                //Json.SaveExt<Flow>(Path + flow.Name + ".flow", flow);

                SharpSerializer serializer = new SharpSerializer();
                serializer.Serialize(flow, Path + flow.Name + ".xml");

            }
            //保存全局变量
            VarMgr.Ins.SaveDic(VarMgr.FlowVars, VarPath + "FlowVars.xml");
        }

        public void LoadFlows()
        {
            var files = Directory.GetFiles(Path, "*.xml");
            foreach (var file in files)
            {
                try
                {
                    //var flow = Json.LoadExt<Flow>(file);
                    SharpSerializer serializer = new SharpSerializer();
                    Flow flow = (Flow) serializer.Deserialize(file);
                    if (flow!=null)
                    {
                        Flows.Add(flow);
                    }
                }
                catch (Exception e)
                {
                       UIMessageBox.ShowError($"加载流程是发现错误，流程名称{file}\r{e.Message}");
                        
                }
            }
            //加载全局变量
            VarMgr.Ins.LoadDic(VarMgr.FlowVars, VarPath + "FlowVars.xml", true);

        }

        public Flow GetFlow(string flowName)
        {
            return Flows.Find(flow => flow.Name == flowName);
        }
    }
}
    